// Copyright 2007 Google Inc.
// All Rights Reserved.

package com.google.jessewilson.codesearch.gtagssearch;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Encapsulates the logic and constants for building gtags search commands.
 *
 * @author Ted Mao (tmao@google.com)
 */
class GtagsCommand {

  /**
   * Arguments always passed to the gtags executable
   *
   * -p plain output
   * -i match invocations instead of definitions
   * -w match whole words only
   * --nocolor do not use ansi color codes
   */
  static final String[] STANDARD_ARGUMENTS = new String[] {
      "-p", "-w", "--nocolor"
  };

  /**
   * Flag used to specify the language of source files to search in
   */
  static final String LANGUAGE_FLAG = "-L";

  /**
   * Flag used to specify gtags proxy server, e.g. "webcache:8080"
   */
  private static final String PROXY_FLAG = "--proxy";

  static final String FIND_INVOCATIONS_FLAG = "-i";

  /**
   * Builds a command that can be passed to {@link ProcessBuilder}.
   *
   * @param executable path to the gtags executable,
   *   e.g. <code>/usr/local/bin/gtags.sh</code>
   * @param tag the tag to search for
   * @oaram languageType the language to search for, or gtags' default language
   *   if null.
   * @param findInvocations whether or not to find invocations instead of
   *   definitions of the tag
   * @return a command that can be passed to {@link ProcessBuilder}.
   */
  public static List<String> buildCommand(String executable, String tag,
      GtagsLanguageType languageType, boolean findInvocations) {
    if (executable == null) {
      throw new IllegalArgumentException("Executable must not be null");
    }
    if (tag == null || tag.length() == 0) {
      throw new IllegalArgumentException("Tag must not be null");
    }

    List<String> command = new ArrayList<String>();
    command.add(executable);
    command.addAll(Arrays.asList(STANDARD_ARGUMENTS));

    if (languageType != null) {
      command.add(LANGUAGE_FLAG);
      command.add(languageType.getLanguageType());
    }

    if (findInvocations) {
      command.add(FIND_INVOCATIONS_FLAG);
    }

    command.add(tag);

    return command;
  }

}
